package com.internet;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 实现TCP的网络编程
 * 例题3:从客户端发送文件到服务器，服务端保存到本地。并返回"发送成功"给客户端
 * 并关闭响应的连接。
 */
public class TCPTest3 {

    @Test
    public void client() throws IOException {

        InetAddress byName = InetAddress.getByName("127.0.0.1");

        Socket socket = new Socket(byName, 8899);

        OutputStream outputStream = socket.getOutputStream();

        FileInputStream fileInputStream = new FileInputStream(new File("蝙蝠侠2.ico"));

        byte[] buffer = new byte[1024];
        int len;

        while ((len = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }

        //关闭数据的输出,解除服务器端阻塞的占用情况
        socket.shutdownOutput();

        //接收来自服务器的数据，显示到控制台上
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        byte[] buffer01 = new byte[1024];

        int len1;

        while ((len1 = inputStream.read(buffer01)) != -1) {
            byteArrayOutputStream.write(buffer01, 0, len1);
        }
        System.out.println(byteArrayOutputStream.toString());


        //关闭资源
        fileInputStream.close();
        socket.close();
        outputStream.close();


    }



    @Test
    public void server() throws IOException {

        ServerSocket serverSocket = new ServerSocket(8899);

        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();

        FileOutputStream fileOutputStream = new FileOutputStream(new File("蝙蝠侠991.ico"));

        byte[] buffer = new byte[1024];

        int len;
        //这里read是一个阻塞式的方法
        while ((len = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
        }

        //增加一步返回消息给客户端
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("你好，美女，照片我已收到，非常漂亮".getBytes());

    }
}
